package com.qf.tenant.service.impl;

import cn.hutool.crypto.SecureUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.device.util.MD5Util;
import com.qf.pck.entity.Package;
import com.qf.pck.entity.PackageTenantPerms;
import com.qf.pck.mapper.PackageMapper;
import com.qf.pck.mapper.PackageTenantPermsMapper;
import com.qf.tenant.dto.TenantDto;
import com.qf.tenant.entity.Tenant;
import com.qf.tenant.mapper.TenantMapper;
import com.qf.tenant.service.TenantService;
import com.qf.utils.JWTUtil;
import com.qf.vo.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 租户表 服务实现类
 * </p>
 *
 * @author wxh
 * @since 2023-10-28
 */
@Service
public class TenantServiceImpl extends ServiceImpl<TenantMapper, Tenant> implements TenantService {
    @Autowired
    private PackageTenantPermsMapper ptpMapper;
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private PackageMapper packageMapper;
    @Autowired
    private PackageTenantPermsMapper packageTenantPermsMapper;

    /**
     * 租户登录
     *
     * @param tenant
     * @return
     */
    @Override
    public R tenantLogin(Tenant tenant) {
        //首先判断传的参数是否错误
        if (tenant == null) {
            return R.fail("参数无效");
        }
        //用户名去数据库查询是否存在
        QueryWrapper<Tenant> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Tenant::getName, tenant.getName());
        Tenant dbTenant = this.baseMapper.selectOne(queryWrapper);
        if (dbTenant == null) {
            return R.fail("用户名或者密码错误");
        }
        if(dbTenant.getEnable()!=1){
            return new R<>(false,501,"用户禁止登录！请联系管理员",null);
        }

        //加密密码
        String md5 = SecureUtil.md5(tenant.getPwd());
        //判断密码
        if (!md5.equals(dbTenant.getPwd())) {
            return R.fail("用户名或者密码错误");
        }
        List<Package> packages = this.baseMapper.findPermsById(dbTenant.getId());
        int price = 0;
        for (Package p : packages) {
            if (p.getPrice() > price) {
                price = p.getPrice();
            }
        }
        if(price!=0){
            String permIds = packageMapper.selectPackage(price).getPermIds();
            List<String> permIdsList = JSONUtil.toList(permIds, String.class);
            List<PackageTenantPerms> collect = permIdsList.stream().map(id -> {
                return packageTenantPermsMapper.selectById(id);
            }).collect(Collectors.toList());
            ArrayList<String> arrayList = new ArrayList<>();
            for (int i = 0; i < collect.size(); i++) {
                String permName = collect.get(i).getPermName();
                arrayList.add(permName);
                dbTenant.setPerms(arrayList);
            }
        }






        dbTenant.setPwd("");

        String token = JWTUtil.generatorHoursToken(dbTenant, 2);
        return R.ok(token,"登录成功");
    }

    @Override
    public R tenantRegister(TenantDto<Tenant> tenantDto) {
        Tenant tenant = tenantDto.getTenant();
        String code = tenantDto.getCode();
        String s = stringRedisTemplate.boundValueOps("code_" + tenant.getPhone()).get();
        if (s != null && !"".equals(s)) {
            if (code.equals(s)) {
                String idStr = IdWorker.getIdStr();
                tenant.setPwd(MD5Util.MD5Encode(tenant.getPwd()));
                tenant.setId(idStr);
                tenant.setEnable( 1);
                tenant.setCreateTime(new Date());
                tenant.setUpdateTime(new Date());
                tenant.setDeleted((byte) 0);
                tenant.setAccessKey(idStr);
                tenant.setAccessSecurit(MD5Util.MD5Encode(idStr));
                tenant.setAuditStatus(1);
                int insert = this.baseMapper.insert(tenant);
                if ((insert > 0)) {
                    return R.ok("注册成功");
                }
                return R.fail("注册失败");
            }
            new R(false, 501, "验证码错误", null);
        }
        return new R(true, 201, "验证码已过期", null);
    }
}
